//
//  YSPrizeViewController.m
//  Yaoyle
//
//  Created by ZhaoXudong on 14-9-24.
//  Copyright (c) 2014年 ZhaoXudong. All rights reserved.
//

#import "YSPrizeViewController.h"
#import "YSPrizeInfoView.h"
#import "YSPrizeModel.h"


static NSInteger nAbandonPrizeTag = 100;
static NSInteger nAbandonPrizeExitTag = 101;

@interface YSPrizeViewController () <UITextFieldDelegate, UIAlertViewDelegate> {
    NSArray *prizeInfoArray;
    __weak IBOutlet UIScrollView *scrollView;
    __weak IBOutlet UIImageView *leftView;
    
    __weak IBOutlet UIView *btnView;
    __weak IBOutlet UIView *addressInfoView;
    
    
    __weak IBOutlet UITextField *phoneTextField;
    __weak IBOutlet UITextField *addressTextField;
    
    NSMutableArray *prizeViewArray;
    
    BOOL isCanPrize;
    NSInteger prizeScore;
    
    NSString *receiveKey;
    NSInteger prizeType;
    
    UIView *prizeDoneView;
}

@end

@implementation YSPrizeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        prizeViewArray = [NSMutableArray array];
        
        isCanPrize = NO;
        prizeScore = 0;
        receiveKey = nil;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    addressInfoView.hidden = YES;
    btnView.hidden = YES;
    
    for (NSInteger nRow = 0; nRow < 3; nRow ++) {
        for (NSInteger nColumn = 0; nColumn < 4; nColumn++) {
            if (nRow == 1) {
                if (nColumn == 1) {
                    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                    [btn setFrame:CGRectMake((leftView.right + 20) + 80 * nColumn ,
                                             80 * nRow + 20, 160, 80)];
                    [btn setImage:[UIImage imageNamed:@"prize_btn_n"] forState:UIControlStateNormal];
                    [btn setImage:[UIImage imageNamed:@"prize_btn_h"] forState:UIControlStateHighlighted];
                    [btn addTarget:self action:@selector(startPrize) forControlEvents:UIControlEventTouchUpInside];
                    [scrollView addSubview:btn];
                    continue;
                }
                
                if (nColumn == 2) {
                    continue;
                }
            }
            YSPrizeInfoView *view = [[YSPrizeInfoView alloc] initWithPoint:CGPointMake((leftView.right + 20) + 80 * nColumn ,
                                                                                       80 * nRow + 20)];
            [scrollView addSubview:view];
            [prizeViewArray addObject:view];
        }
    }
    
    [self getPrizeList];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark -

- (IBAction)getPrize:(id)sender {
    if (prizeType != ePrizeScore) {
        // 填写是否地址
        if (phoneTextField.text.length == 0) {
            [self showMsgWithTitle:nil msg:@"请输入手机号码"];
            return;
        }
        
        if (addressTextField.text.length == 0) {
            [self showMsgWithTitle:nil msg:@"请输入地址"];
            return;
        }
    }
    [YSProgressHUD showHUDAddedTo:self.view];
    [[NetworkMgr sharedManager] asynchRequestWithFunId:eAPI_PRIZE_INFO
                                              delegate:self
                                                params:@{@"receiveKey’":receiveKey,
                                                         @"mobile":phoneTextField.text,
                                                         @"address":addressTextField.text}];
}

- (IBAction)abandonPrize:(id)sender {
    receiveKey = nil;
    addressInfoView.hidden = YES;
    btnView.hidden = YES;
}

- (IBAction)back:(id)sender {
    if (![YSUtility isBlankObject:receiveKey]) {
        [self showMsgWithTitle:nil msg:@"您有奖品没有领取，确定要放弃吗？" delegate:self tag:nAbandonPrizeExitTag];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)startPrize {
    
    if (!isCanPrize) {
        return;
    }
    
    if (![YSUtility isBlankObject:receiveKey]) {
        [self showMsgWithTitle:nil msg:@"xx" delegate:self tag:nAbandonPrizeTag];
        return;
    }
    
    addressInfoView.hidden = YES;
    btnView.hidden = YES;
    NSString *msg = [NSString stringWithFormat:@"参与抽奖将扣除您的%d幸运豆\r是否继续?",prizeScore];
    [self showMsgWithTitle:nil msg:msg delegate:self tag:eAPI_PRIZE_LOTTERY];
}

- (void)getPrizeList {
    [YSProgressHUD showHUDAddedTo:self.view];
    [[NetworkMgr sharedManager] asynchRequestWithFunId:eAPI_PRIZE_LIST
                                              delegate:self
                                                params:@{@"uid":[YSGlobal getUID]}];
}

// 中奖弹出
- (void)showOrderPrizeView:(NSDictionary *)dict prizeType:(ePrizeType)type{
    prizeDoneView = [[UIView alloc] initWithFrame:CGRectMake(0, 320, self.view.frame.size.width, self.view.frame.size.height)];
    prizeDoneView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:prizeDoneView];
    // 320  230
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((UI_SCREEN_HEIGHT - 320) / 2,
                                                                           (UI_SCREEN_WIDTH - 240)/2,
                                                                           320, 240)];
    imageView.image = [UIImage imageNamed:@"prize_order_bg"];
    [prizeDoneView addSubview:imageView];
    [prizeDoneView sendSubviewToBack:imageView];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake((UI_SCREEN_HEIGHT - 220)/2, imageView.bottom - 10, 220, 50)];
    [btn setBackgroundImage:[UIImage imageNamed:@"prize_win_n"] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"prize_win_h"] forState:UIControlStateHighlighted];
    if (type == ePrizeScore) {
        [btn setTitle:@"继续抽奖" forState:UIControlStateNormal];
    } else {
        [btn setTitle:@"赶紧点击去领奖喽" forState:UIControlStateNormal];
    }
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(hidePrizeDoneView) forControlEvents:UIControlEventTouchUpInside];
    [prizeDoneView addSubview:btn];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake((UI_SCREEN_HEIGHT - 320) / 2,
                                                               btn.top - 30,
                                                               320, 20)];
    title.backgroundColor = [UIColor clearColor];
    title.text = [NSString stringWithFormat:@"恭喜你获得了%@ X1",dict[@"name"]];
    title.font = [UIFont systemFontOfSize:14];
    title.textAlignment = NSTextAlignmentCenter;
    title.textColor = [UIColor whiteColor];
    [prizeDoneView addSubview:title];
    [prizeDoneView bringSubviewToFront:title];
    
    UIImageView *subImageView = [[UIImageView alloc] initWithFrame:CGRectMake((UI_SCREEN_HEIGHT - 90) / 2,
                                                                              title.top - 100,
                                                                              90, 90)];
    if ([YSUtility isBlankObject:dict[@"photo"]]) {
        subImageView.image = [UIImage imageNamed:@"raffle_query"];
    } else {
        NSURL *url = [[NSURL alloc] initWithString:dict[@"photo"]];
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
        subImageView.backgroundColor = [UIColor grayColor];
        subImageView.image = image;
    }
    [prizeDoneView addSubview:subImageView];
    
    [UIView animateWithDuration:.5 animations:^{
        [prizeDoneView setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    }];
}

- (void)hidePrizeDoneView {
    [UIView animateWithDuration:.5 animations:^{
        [prizeDoneView setFrame:CGRectMake(0, 320, self.view.frame.size.width, self.view.frame.size.height)];
    } completion:^(BOOL finished) {
        [prizeDoneView removeFromSuperview];
        prizeDoneView = nil;
    }];
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [scrollView setContentOffset:CGPointMake(0, 140) animated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - NetWorkDelegate

- (void)didSuccess:(NetworkMgr *)api userInfo:(NSDictionary *)info {
    [YSProgressHUD hideHUDForView:self.view];
    
    NSInteger funId = [info[kFUN_ID] integerValue];
    NSDictionary *re = info[API_Result_RE];
    if ([YSUtility isBlankObject:re]) {
        return;
    }
    
    if ([info[@"status"] integerValue] != 200) {
        [self showToastMessage:info[@"msg"]];
        return;
    }
    
    re = [YSUtility returnDictionary:re];
    if (funId == eAPI_PRIZE_LIST) {
        NSArray *array = re[@"prizeList"];
        isCanPrize = YES;
        prizeScore = [re[@"score"] integerValue];
        
        if (array.count != 0) {
            int nIndex = 0;
            for (YSPrizeInfoView *view in prizeViewArray) {
                if (nIndex == array.count) {
                    break;
                }
                YSPrizeModel *model = [[YSPrizeModel alloc] initWithDict:[array objectAtIndex:nIndex]];
                [view setPrizeModel:model];
                nIndex++;
            }
        }
    } else if (funId == eAPI_PRIZE_LOTTERY) {
        NSInteger isOrder = [re[@"isorder"] integerValue];
        if (isOrder == 1) {
            prizeType = [re[@"type"] integerValue];
            
            if (prizeType != ePrizeScore) {
                // 需要填写地址
                receiveKey = re[@"receiveKey"]; // 需要领取
                
                btnView.hidden = NO;
                addressInfoView.hidden = NO;
            }
            // 中奖
            [self showOrderPrizeView:re prizeType:prizeType];
        } else {
            // 没中奖
        }
    } else if (funId == eAPI_PRIZE_INFO){
        receiveKey = nil;
        btnView.hidden = YES;
        addressTextField.text = nil;
        phoneTextField.text = nil;
        addressInfoView.hidden = YES;
    }
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == alertView.cancelButtonIndex) {
        return;
    }
    
    if (alertView.tag == eAPI_PRIZE_LOTTERY) {
        [[NetworkMgr sharedManager] asynchRequestWithFunId:eAPI_PRIZE_LOTTERY
                                                  delegate:self
                                                    params:@{@"uid":[YSGlobal getUID]}];
    } else if (alertView.tag == nAbandonPrizeTag) {
        receiveKey = nil;
    } else if (alertView.tag == nAbandonPrizeExitTag) {
        receiveKey = nil;
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}
@end
